package cn.signalpha.common.wechat.handler;

import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.com.entity.UserOauth;
import cn.signalpha.modules.com.entity.enums.UserSourceEnum;
import cn.signalpha.modules.com.service.UserOauthService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Slf4j
@Component
@AllArgsConstructor
public class UnsubscribeHandler extends AbstractHandler {

	private final UserOauthService userOauthService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String openId = wxMessage.getFromUser();
		logger.info("取消关注用户 OPENID: " + openId);
		UserOauth userOauth = userOauthService.getByOpenIdAndSource(openId, UserSourceEnum.WECHAT_PUBLIC.getValue());
		if(ObjectUtil.isNotEmpty(userOauth)){
			//更新关注状态
			userOauthService.updateById(UserOauth.builder().id(userOauth.getId()).status(0).build());
			userOauthService.removeCaCheByOpenIdAndSource(userOauth.getOpenId(), userOauth.getSource());
		}
        return null;
    }

}
